package com.example.demo.config;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

public class NullvalueHandlerFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Map<String, String[]> parameterMap = new HashMap<>(servletRequest.getParameterMap());

        // 删除请求参数为空的参数，例如 /test?a=&b=&c=&d=，默认只取第一个参数，不接受 /test?a=&a=2数组形式
        parameterMap.values().removeIf(value -> "".equals(value[0].trim()));

        NullValueHandlerRequestWrapper wrapper =new NullValueHandlerRequestWrapper((HttpServletRequest)servletRequest);
        wrapper.setParameterMap(parameterMap);
        // 获得重写后的请求
        filterChain.doFilter(wrapper, servletResponse);
    }

}
